package com.tougutips.auth.service;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.tougutips.auth.api.RemoteUserInfoService;
import com.tougutips.common.core.constant.TokenConstants;
import com.tougutips.common.redis.service.RedisService;
import com.tougutips.common.user.vo.LoginVO;
import com.tougutips.common.utils.JWTUtil;
import com.tougutips.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginService{
    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    /**
     * 登录与注册业务,业务待优化
     *
     * @param loginVO 登录用户VO
     * @return 响应体
     */
    public AjaxResult login(LoginVO loginVO) {
        String verify = loginVO.getVerify();
        String account = loginVO.getAccount();
        // 判断传入账户参数是否为空
        if (!StringUtil.isNotEmpty(account) || !StringUtil.isNotEmpty(verify)) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED.value(),"手机号或者验证码为空!");
        }
        // 获取redis中账号对应的验证码
        Object msg_code = redisService.getCacheObject(account);
        // 判断redis中获取的验证码是否为空,为空则表示验证码过期或者传入手机号没有发送验证码
        if (StringUtil.isEmpty(msg_code)) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED.value(),"请重新获取验证码!");
        }
        // 判断redis验证码与前台传入验证码是否一致,一致则进行注册业务操作
        if (!verify.equals(msg_code)) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED.value(),"验证码错误!");
        }
        // 删除redis手机验证码
        redisService.deleteObject(account);
        // 查询是否存在此用户
        AjaxResult rest = remoteUserInfoService.getUserByAccount(account);
        Object user = rest.get("data");
        // 用户不存在,进入注册流程
        if (StringUtil.isEmpty(user)) {
            rest = remoteUserInfoService.addUser(account);
            user = rest.get("data");
            if(StringUtil.isEmpty(user)){
                return AjaxResult.error("用户注册失败");
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put(TokenConstants.ACCOUNT,account);
        map.put(TokenConstants.USER,user);
        // 生成token
        String token = JWTUtil.sign(map);
        map.put(TokenConstants.TOKEN,token);
        // 放入redis
        redisService.setCacheObject(account, token, 7L, TimeUnit.DAYS);
        return AjaxResult.success(map);
    }
}
